// 2023年十月活动相关方法
// 主要是各页面通用的方法

import { reqCreateTeam, reqTeamCheckIn } from '@/api/activity-202310-api';
import { reqUploadImage } from '@/api/api-others';
import type CheckInSuccessPopup from '@/components/CheckInSuccessPopup.vue';
import type CreateTeamPopup from '@/components/CreateTeamPopup.vue';
import { useActivity202310 } from '@/stores/activity-202310-store';
import { useUser } from '@/stores/user';
import dayjs from 'dayjs';
import type { ComponentInternalInstance } from 'vue';
import { navigateTo } from './navigate';

const userStore = useUser();
const { userInfo } = storeToRefs(userStore);

const activity202310Store = useActivity202310();
const {
  personInfo202310,
  teamInviteCompetition,
} = storeToRefs(activity202310Store);

const { setPersonInfo202310, setTeamInviteCompetitionData } = activity202310Store;

/** 「创建团队」弹窗确定创建事件回调
 * @returns 是否创建成功
 */
export const onCreateTeamConfirm = async ({ name, avatar }: {name:string, avatar:string}) => {
  const avatarUrl = (await reqUploadImage(avatar)).fileUrl;
  const createTeamResData = (await reqCreateTeam(
    name,
    avatarUrl,
  ))?.data as ResponseData<{msg: string, code: 200|201}>;
  if (createTeamResData?.data.code === 200) {
    navigateTo('my-team');
    uni.showToast({
      title: '创建成功',
      icon: 'success',
    });
    // 创建成功后，重新获取团队相关信息
    setPersonInfo202310();
    setTeamInviteCompetitionData();
    return true;
  }
  uni.showToast({
    title: createTeamResData?.data.msg || '创建失败，请稍后重试',
    icon: 'none',
  });
  return false;
};

/** 点击「立即签到」按钮
 * @param currentInstance 当前页面实例
 */
export const clickCheckIn = async (currentInstance: ComponentInternalInstance | null) => {
  if (userInfo.value.nickname.length === 0) {
    navigateTo('login');
    return;
  }
  if (!personInfo202310.value.isJoinTeam) {
    uni.showModal({
      title: '提示',
      content: '您还没有团队，组建团队后再签到哦～',
      confirmText: '创建团队',
      success: (res) => {
        if (res.confirm) {
          const createTeamPopup = currentInstance?.refs
            .createTeamPopup as typeof CreateTeamPopup;
          createTeamPopup?.open();
        }
      },
    });
    return;
  }

  if (teamInviteCompetition.value?.isCheckIn) {
    uni.showToast({ title: '今日已签到' });
    return;
  }

  const checkInResData = (await reqTeamCheckIn())?.data as ResponseData<{code: 200|203 }>;
  if (checkInResData?.code === 200) {
    const checkInSuccessPopup = currentInstance?.refs
      .checkInSuccessPopup as typeof CheckInSuccessPopup;
    checkInSuccessPopup?.open();
    setTeamInviteCompetitionData();
    return;
  }

  uni.showToast({ title: checkInResData.msg || '签到失败，请稍后重试' });
};

/** 邀请好友通用分享回调 */
export const inviteFriend = () => ({
  title: `@${personInfo202310.value.nickname}邀请您参加嗨喵十月巅峰赛活动,赢取iphone16 Pro大奖>>`,
  path: `/pages/index?inviteKey=${personInfo202310.value.inviteKey}`,
  imageUrl: 'https://ustatic.hudongmiao.com/miao/wxt/person1.png',
});

/** 邀请加入队伍通用逻辑 */
export const inviteJoinTeam = () => ({
  imageUrl: 'https://ustatic.hudongmiao.com/miao/wxt/team2.png',
  title: `@${personInfo202310.value.nickname}邀请您加入Ta的团队 "${teamInviteCompetition.value?.teamName}",赢取万元现金红包!`,
  path: `/pages/index?teamId=${teamInviteCompetition.value?.teamId}&teamName=${teamInviteCompetition.value?.teamName}&inviterOfJoinTeam=${personInfo202310.value.nickname}`,
});

/** 订阅消息通用逻辑 */
export const subscribeMessage = () => {
  const lastSubscribeDate = uni.getStorageSync('lastSubscribeDate');
  const nowDate = dayjs().format('YYYY-MM-DD');
  if (lastSubscribeDate !== nowDate) {
    uni.requestSubscribeMessage({
      tmplIds: ['gLOsMeuo1YEEDW9EhBfsbSG190_sK0CdvX3U_dIS2NQ'],
      success: () => {
        console.log('接口调用成功');
        uni.setStorageSync('lastSubscribeDate', nowDate);
      },
      fail: (e) => {
        console.log('接口调用失败', e);
      },
    });
  }
};
